﻿

package we3d.samples.loading {
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	import we3d.View3d;
	import we3d.Scene3d;
	import we3d.scene.LightGlobals;
	import we3d.renderer.realistic.ClipFrustum;
	import we3d.scene.SceneLight;
	import we3d.material.FlatLightAttributes;
	import we3d.rasterizer.IRasterizer;
	import we3d.rasterizer.NativeFlatLight;
	import we3d.loader._3DSLoader;
	import we3d.samples.UserCamera;
	import we3d.layer.GradientBackdrop;
	
	public class Max3DSDemo extends Sprite {
		
		public function Max3DSDemo () {}
		
		public var view:View3d;
		public var scene:Scene3d;
		public var ucam:UserCamera;
		public var lightGlobals:LightGlobals;
		
		public function init () :void {
			
			scene = new Scene3d();
			scene.cam.initProjection( 0.9, 0.1, 100, 550, 400);
			scene.cam.transform.setPosition (-1,2,-4);
			scene.cam.transform.setRotation (Math.PI/9, 0, 0);
			
			lightGlobals = new LightGlobals();
			lightGlobals.ambientLight = 5;
			lightGlobals.ambientColor = 0x0099FF;
			
			var light1:SceneLight = new SceneLight(true);
			light1.intensity = 0.35;
			light1.color = 0xff9933;
			light1.transform.setPosition(0, 1000, -500);
			
			lightGlobals.lightList.push(light1);
			
			view = new View3d(550, 400);
			view.scene = scene;
			view.renderer = new ClipFrustum();
			view.firstLayer.backdrop = new GradientBackdrop(0x0, 0x783210, 0x783210, 0x0, 50, 50);
			addChild( view.viewport )
			
			var ldr:_3DSLoader = new _3DSLoader();
			ldr.addEventListener(Event.INIT, init3DS);
			ldr.addEventListener(Event.COMPLETE, complete3DS);
			
			ldr.loadFile("m3ds.3ds");
		}
		
		private function init3DS (e:Event)  :void {
			trace("File downloaded, starting with parse...");
		}
		
		private function complete3DS (e:Event)  :void {
			
			ucam = new UserCamera(view, 0.25);
			
			var ldr:_3DSLoader = _3DSLoader(e.target);
			
			trace("File parsed, " + ldr.objects.length + " objects, "  +  ldr.lights.length + " lights, " + ldr.surfaces.length  +  " surfaces, " + ldr.fileImages.length + " images ");
			
			scene.add( ldr.objects );
			
			if(ldr.numCameras > 0) {
				scene.cam = ldr.cameras[0];
			}
			
			// Prepare surfaces for lighting
			var r:NativeFlatLight = new NativeFlatLight();
			
			// assign lighting attributes to all surfaces
			for(var i:int=0; i<ldr.surfaces.length; i++) {
				ldr.surfaces[i].attributes = new FlatLightAttributes( ldr.surfaces[i].attributes.color, 1, 0, 1, lightGlobals);
				ldr.surfaces[i].rasterizer = r;
			}
			
			scene.invalidate();
		}
	}
}